function format(text, width) {
    var words = text.split(' ');
    var out = [];
    var line = [];
    for (x of words) {
        line.push(x);
        if (line.join(' ').length > width) {
            line.pop();
            out.push(line.join(' '));
            line.length = 0;
            line.push(x);
        }
    }
    out.push(line.join(' '))
    return out.join('\n')
}

text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam nec consectet" +
    "ur risus. Cras vel urna a tellus dapibus consequat. Duis bibendum tincidunt viverra. Ph" +
    "asellus dictum efficitur sem quis porttitor. Mauris luctus auctor diam id ultrices. Pra" +
    "esent laoreet in enim ut placerat. Praesent a facilisis turpis.";
format(text, 30)